package com.liy.jiagou.sso.auth.config;


// import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


// security
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

//import javax.sql.DataSource;



/**
 *  安全配置  这里全部都是  org.springframework.security 包下的配置
 *
 *
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 数据源 DataSource
     */
//    @Autowired
//    private DataSource dataSource;


    // 注册 AuthenticationManager 实例
    @Override
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     * 配置 AuthenticationManagerBuilder
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.jdbcAuthentication().dataSource(dataSource);   // 这里保存到 数据库

        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("zw").password("1024").authorities("ROLE_USER", "pw.add","pw.query")    //
                .and()
                .withUser("bs").password("1024").authorities( "ROLE_USER",  "sys.add","sys.query")    //
                .and()
                .withUser("liy").password("1024").authorities("ROLE_ADMIN", "product.add","product.query");   //
    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                //.antMatchers( "/oauth/*", "/token/*" , "/oauth/check_token").permitAll()   // 这些可以打开
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic()
                .and()
                .csrf().disable()
        ;
    }


}
